package com.le.edu.handler;

import com.le.edu.exception.AppException;
import com.le.edu.exception.NeedLoginException;
import com.le.edu.resp.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice //这是集中处理 controller 异常的处理器
public class AppExceptionHandler {
    @ResponseStatus(HttpStatus.FORBIDDEN)  //这种异常，自定义响应状态码
    @ExceptionHandler(NeedLoginException.class)
    public Result<Object> needLoginPetStoreException(NeedLoginException exception) {
        //业务抛出的错误码
        Integer code = exception.getCode();
        //业务抛出的异常信息
        String message = exception.getMessage();
        Result<Object> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    /**
     * 所有业务抛出的 业务异常，都由这个方法处理
     *
     * @return
     */
    @ExceptionHandler(AppException.class)
    public Result<Object> petStoreException(AppException exception) {
        //业务抛出的错误码
        Integer code = exception.getCode();
        //业务抛出的异常信息
        String message = exception.getMessage();
        Result<Object> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        return result;
    }
}
